/* eslint-disable react-refresh/only-export-components */
import type { FC } from 'react'
import { Suspense } from 'react'
import { getCateListApi, postCateApi, putCateApi, delCateApi } from '@/api/cate-api.ts'
import to from 'await-to-js'
import { useLoaderData, defer, Await } from 'react-router-dom'
import type { ActionFunctionArgs } from 'react-router-dom'
import { Table, Space, message, Spin } from 'antd'
import type { TableProps } from 'antd'
import ButtonAdd from '@/components/article-cate/btn-add'
import ButtonEdit from '@/components/article-cate/btn-edit'
import ButtonDelete from '@/components/article-cate/btn-del'
import type { Method } from 'axios'

const columns: TableProps<CateItem>['columns'] = [
  {
    title: '序号',
    render(_, __, index) {
      return index + 1
    }
  },
  {
    title: '分类名称',
    dataIndex: 'cate_name'
  },
  {
    title: '分类别名',
    dataIndex: 'cate_alias'
  },
  {
    title: '操作',
    render(_, record) {
      return (
        <>
          <ButtonEdit cate={record} />
          <ButtonDelete id={record.id} />
        </>
      )
    }
  }
]

const ArticleCate: FC = () => {
  const loaderData = useLoaderData() as { result: BaseResponse<CateItem[]> }

  return (
    <Space direction="vertical" style={{ display: 'flex' }}>
      <ButtonAdd />

      {/* 异步加载分类数据，请求期间展示 loading 占位符 */}
      <Suspense
        fallback={
          <Spin>
            <Table />
          </Spin>
        }
      >
        <Await resolve={loaderData.result} errorElement="分类数据加载失败，请稍后再试！">
          {({ data }) => <Table dataSource={data} columns={columns} rowKey="id" bordered size="middle" pagination={false} />}
        </Await>
      </Suspense>
    </Space>
  )
}

export default ArticleCate

export const loader = () => {
  return defer({ result: getCateListApi() })
}

export const action = async ({ request }: ActionFunctionArgs) => {
  const fd = await request.formData()
  const method = request.method.toUpperCase() as Method

  if (method === 'POST') {
    const [err] = await to(postCateApi(fd))
    if (err) return null
    message.success('添加成功!')
  } else if (method === 'PUT') {
    const [err] = await to(putCateApi(fd))
    if (err) return null
    message.success('修改成功!')
  } else if (method === 'DELETE') {
    const [err] = await to(delCateApi(fd))
    if (err) return null
    message.success('删除成功!')
  }

  return true
}
